package cn.yunhe.dao.Impl;

import cn.yunhe.dao.IVoteDao;
import cn.yunhe.util.ConnectionPool;
import cn.yunhe.entity.Vote;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class IVoteDaoImpl implements IVoteDao {
    @Override
    public int vote(Vote vote) {
        Connection conn = null;
        PreparedStatement sts = null;
        int flag = -1;  //定义一个变量接收处理结果
        StringBuilder sql = new StringBuilder();
        sql.append(" update vote");
        sql.append(" set times = times +10");
        sql.append(" where itemName = ?");

        try {
            conn = ConnectionPool.getConnection(); //获取数据连接
            sts = conn.prepareStatement(sql.toString()); //预编译sql语句
            sts.setString(1, vote.getItemName());
            flag = sts.executeUpdate();  //执行查询方法
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(sts, conn); //关闭连接池
        }
        return flag;
    }

    @Override
    public List<Vote> selectAllVote() {
        Connection conn = null;
        PreparedStatement sts = null;
        ResultSet rs = null;
        List<Vote> list = new ArrayList<Vote>();
        StringBuilder sql = new StringBuilder();
        sql.append(" select*");
        sql.append(" from vote");

        try {
            conn = ConnectionPool.getConnection();
            sts = conn.prepareStatement(sql.toString());
            rs = sts.executeQuery();
            while (rs.next()){
                list.add(new Vote(
                        rs.getInt("itemId"),
                        rs.getString("itemName"),
                        rs.getInt("times")
                ));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(sts,conn);
        }
        return list;
    }
}
